package com.qiantu.phone.ui.fragment.device;

import android.annotation.SuppressLint;
import android.webkit.WebSettings;
import android.widget.FrameLayout;

import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.PlayInfoBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.jsbridge.AndroidToJs;
import com.qiantu.phone.widget.BrowserView;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * desc   : 可视门铃
 */
public final class DoorBellFragment extends BaseDeviceFragment implements AndroidToJs.OnJsToJavaMethodEventListener{
    private String httpUrl = "https://ysdebug.thinkhome.com.cn/ysh5/#/";
    private String ACCESSTOKEN = "?accessToken=";
    private String VIDEOURL = "&videoUrl=";
    private String ROOMNAME = "&roomName=";
    private BrowserView mWebView;
    private FrameLayout frameLayout;
    private StringBuilder stringBuilder;


    public static DoorBellFragment newInstance(){
        DoorBellFragment fragment = new DoorBellFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_doorbell;
    }

    @Override
    protected void initView() {
        super.initView();
        mWebView = findViewById(R.id.doorbell_webview);
        frameLayout = findViewById(R.id.content_view);
        initPlayInfo();
    }

    private void initPlayInfo() {
        LLHttpManager.getPlayInfo(this,mDevice.getDeviceSerialNo(),new HttpCallback<HttpData<PlayInfoBean>>(this){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<PlayInfoBean> result) {
                super.onSucceed(result);
                PlayInfoBean data = result.getData();
                DeviceBean deviceBean = LLDeviceDBManager.getInstance(getContext()).get(result.getData().getDeviceSerialNo());
                stringBuilder = new StringBuilder(httpUrl);
                stringBuilder.append(ACCESSTOKEN)
                        .append(data.getAccessToken())
                        .append(VIDEOURL)
                        .append(data.getAddress())
                        .append(ROOMNAME)
                        .append(deviceBean.getRoomName());
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
                initWebview();
            }
        });
    }


    @SuppressLint("SetJavaScriptEnabled")
    private void initWebview() {
        WebSettings settings = mWebView.getSettings();
        mWebView.getSettings().setLoadsImagesAutomatically(true);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        //控制WebView 自适应屏幕
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//        // 设置 WebView 生命管控
//        mWebView.setLifecycleOwner(this);
        mWebView.addJavascriptInterface(new AndroidToJs(this), "android");
        if (stringBuilder!=null){
            mWebView.loadUrl(stringBuilder.toString());
        }


    }

    protected void updateView() {
        super.updateView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        frameLayout.removeAllViews();
        if (mWebView!=null){
            mWebView.clearHistory();
            mWebView.clearCache(true);
            mWebView.freeMemory();
            mWebView.destroy();
            mWebView = null;
        }
    }

    @Override
    public void onMethodEvent(int type, String url) {
        switch (type) {
            case TO_BACK:
                finish();
                break;
            case OPEN_DOOR:
                Map<String,Object> map=new HashMap<>();
                Map<String,Object> status=new HashMap<>();
                map.put(url,1);
                status.put(STATUS,map);
                LLHttpManager.operationDevice(this,mDevice.getDeviceSerialNo(),status,new HttpCallback<HttpData<Void>>(this){
                    @Override
                    public void onStart(Call call) {
                        if(getContext() != null && getContext() instanceof AppActivity){
                            ((AppActivity) getContext()).showDialog("执行中...");
                        }
                    }

                    @Override
                    public void onSucceed(HttpData<Void> result) {
                        super.onSucceed(result);
                    }

                    @Override
                    public void onFail(Exception e) {
                        ToastUtils.show(R.string.exec_failure);
                    }

                    @Override
                    public void onEnd(Call call) {
                        if(getContext() != null && getContext() instanceof AppActivity) {
                            ((AppActivity) getContext()).hideDialog();
                        }
                    }
                });
                break;
            case CLOSE_ANSWER:
                Map<String,Object> map2=new HashMap<>();
                Map<String,Object> status2=new HashMap<>();
                map2.put(url,1);
                status2.put(STATUS,map2);
                LLHttpManager.operationDevice(this,mDevice.getDeviceSerialNo(),status2,new HttpCallback<HttpData<Void>>(this){
                    @Override
                    public void onStart(Call call) {
                        if(getContext() != null && getContext() instanceof AppActivity){
                            ((AppActivity) getContext()).showDialog("执行中...");
                        }
                    }

                    @Override
                    public void onSucceed(HttpData<Void> result) {
                        super.onSucceed(result);
                    }

                    @Override
                    public void onFail(Exception e) {
                        ToastUtils.show(R.string.exec_failure);
                    }

                    @Override
                    public void onEnd(Call call) {
                        if(getContext() != null && getContext() instanceof AppActivity) {
                            ((AppActivity) getContext()).hideDialog();
                        }
                    }
                });
                break;
        }
    }
}
